package com.zhong.gang.pda.ui.main;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhong.gang.applib.base.act.ActBaseRefresh;
import com.zhong.gang.applib.config.Config;
import com.zhong.gang.applib.http.BaseDataBean;
import com.zhong.gang.applib.http.callback.DataCallBack;
import com.zhong.gang.applib.modle.ListBean;
import com.zhong.gang.applib.pop.TypeBean;
import com.zhong.gang.applib.pop.TypePop;
import com.zhong.gang.applib.ui.view.RightTitleView;
import com.zhong.gang.applib.utils.permission.PermissionCallback;
import com.zhong.gang.applib.utils.permission.PermissionSD;
import com.zhong.gang.pda.R;
import com.zhong.gang.pda.databinding.ActivityMainBinding;
import com.zhong.gang.pda.db.loction.LocationMessageUtils;
import com.zhong.gang.pda.dialog.IntoTypeDialog;
import com.zhong.gang.pda.ui.action.HuoBean;
import com.zhong.gang.pda.ui.action.deliver.DeliverAct;
import com.zhong.gang.pda.ui.action.deliver.controller.DeliverUpDataPersenter;
import com.zhong.gang.pda.ui.action.receive.ReceiveAct;
import com.zhong.gang.pda.ui.action.receive.controller.ReceiveUpDataPersenter;
import com.zhong.gang.pda.ui.mine.MineAct;
import com.zhong.gang.pda.utils.PowerUtilNew;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

public class MainActivity extends ActBaseRefresh<ActivityMainBinding, MainAdapter>
        implements TypePop.onTypeItemClickedListener, BaseQuickAdapter.OnItemClickListener
        , PopupWindow.OnDismissListener, PowerUtilNew.PowerUtilListener, TextWatcher {
    private MainPersenter persenter;
    private IntoTypeDialog intoTypeDialog;

    private ReceiveUpDataPersenter receiveUpDataPersenter;
    private DeliverUpDataPersenter deliverUpDataPersenter;

    protected RightTitleView rightTitleView;
    protected int type = 0, status = 0;
    protected TypePop typePop, statusPop;
    //    private PowerUtil powerUtil;
    private PowerUtilNew powerUtilNew;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            receiveUpDataPersenter.startData(MainActivity.this);
            deliverUpDataPersenter.startData(MainActivity.this);
            handler.sendEmptyMessageDelayed(1, 10 * 60 * 1000);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        powerUtilNew.getDevices();
        powerUtilNew.setGpio();

//        powerUtilNew.open();
    }

    @Override
    public int LayoutRes() {
        return R.layout.activity_main;
    }

    @NonNull
    @Override
    public String CreateTitle() {
        return "中钢料场管理系统";
    }

    @Override
    public void initView() {
//        LocationMessageUtils.getIntent(this).deletAll();
        bind.setAct(this);
        powerUtilNew = new PowerUtilNew(this, this);
        new PermissionSD(this, new PermissionCallback(this) {
            @Override
            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {

//                powerUtil.power( "1" );
//                powerUtil.open();


//                powerUtilNew.getDevices();
//                powerUtilNew.setGpio();
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                powerUtilNew.open();
            }
        });
        persenter = new MainPersenter();
        getTitleBar().getLeftView().setVisibility(View.GONE);
        rightTitleView = new RightTitleView(this);
        rightTitleView.setImgRes(com.zhong.gang.applib.R.mipmap.icon_mine);
        getTitleBar().setRightView(rightTitleView);
        rightTitleView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openActivity(MineAct.class);
            }
        });
        receiveUpDataPersenter = new ReceiveUpDataPersenter();
        deliverUpDataPersenter = new DeliverUpDataPersenter();
        handler.sendEmptyMessage(1);
        initPop();
        bind.searchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    onRefresh();
                    hideKeyboard();
                }
                return false;
            }
        });
        bind.searchEdt.addTextChangedListener(this);
        bind.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        super.initrefrsh(bind.pullto, new MainAdapter(), bind.recyclerView);
        adapter.setOnItemClickListener(this);
        getData();
        getRxManager().add(Config.MAIN, new Consumer<MainBean>() {
            @Override
            public void accept(MainBean mainBean) throws Exception {
                for (int n = 0; n < adapter.getData().size(); n++) {
                    if (adapter.getData().get(n).getId() == mainBean.getId()) {
                        adapter.getData().get(n).setType(mainBean.getType());
                        adapter.notifyItemChanged(n);
                        return;
                    }
                }
            }
        });
    }

    /**
     * 初始话pop和dialog
     */
    private void initPop() {
        intoTypeDialog = new IntoTypeDialog(this);
        List<TypeBean> typeList = new ArrayList<>();
        getTypeList(typeList, "全部", 0);
        getTypeList(typeList, "料场发货", 1);
        getTypeList(typeList, "料场收货", 2);
        getTypeList(typeList, "待处理", 3);
        typePop = new TypePop(this, bind.typeLayout, typeList, this);


        List<TypeBean> statusList = new ArrayList<>();
        getTypeList(statusList, "全部", 0);
        getTypeList(statusList, "场内", 1);
        getTypeList(statusList, "已出场", 2);
        statusPop = new TypePop(this, bind.statusLayout, statusList, this);

        typePop.setOnDismissListener(this);
        statusPop.setOnDismissListener(this);
    }


    /**
     * 获取typeList
     *
     * @param data
     * @param title
     * @param type
     */
    protected void getTypeList(List<TypeBean> data, String title, int type) {
        if (data == null)
            return;
        data.add(new TypeBean(title, type));
    }


    @Override
    public void getData() {
        super.getData();
        persenter.getData(this, page, bind.searchEdt.getText().toString(), type, status, new ActCallBack<BaseDataBean<ListBean<MainBean>>>() {
            @Override
            public void onResponse(BaseDataBean<ListBean<MainBean>> data) throws Exception {
                super.onResponse(data);
                setData(data.getResult().getRecords());
            }
        });
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        MainBean mainBean = (MainBean) adapter.getItem(position);
        switch (mainBean.getType()) {
            case 1://发货
                DeliverAct.openAct(this, mainBean.getId(), false);
                break;
            case 2://收货
                ReceiveAct.openAct(this, mainBean.getId(), false);
                break;
            default:
                HuoBean huoBean = LocationMessageUtils.getIntent(this).getData(mainBean.getId());
                if (huoBean == null)
                    intoTypeDialog.show(mainBean.getId());
                else {
                    switch (huoBean.getType()) {
                        case 1://发货
                            DeliverAct.openAct(this, mainBean.getId(), false);
                            break;
                        case 2://收货
                            ReceiveAct.openAct(this, mainBean.getId(), false);
                            break;
                        default:
                            intoTypeDialog.show(mainBean.getId());
                    }
                }
                break;
        }
    }


    @Override
    public void onTypeItem(View view, TypeBean typeBean) {
        if (typeBean == null)
            return;
        int i = view.getId();
        if (i == R.id.type_layout) {
            type = typeBean.getType();
            bind.typeText.setText(typeBean.getTitle());
        } else if (i == R.id.status_layout) {
            status = typeBean.getType();
            bind.statusText.setText(typeBean.getTitle());
        }

        onRefresh();
    }

    @Override
    public void onDismiss() {
        bind.typeImg.setImageResource(com.zhong.gang.applib.R.mipmap.icon_down);
        bind.statusImg.setImageResource(com.zhong.gang.applib.R.mipmap.icon_down);
    }

    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.type_layout) {
            bind.typeImg.setImageResource(com.zhong.gang.applib.R.mipmap.icon_up);
            typePop.showAsDropDown(bind.typeLayout, type);
        } else if (i == R.id.status_layout) {
            bind.statusImg.setImageResource(com.zhong.gang.applib.R.mipmap.icon_up);
            statusPop.showAsDropDown(bind.statusLayout, status);
        } else if (i == R.id.secect_iv) {
            onRefresh();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        powerUtil.power( "0" );
//        powerUtil.close();
    }

    @Override
    public void onDataReceived(String str) {
        persenter.getData(this, str, new DataCallBack<BaseDataBean<HuoBean>>() {
            @Override
            public void onResponse(BaseDataBean<HuoBean> data) throws Exception {
                super.onResponse(data);
                switch (data.getResult().getType()) {
                    case 1://发货
                        DeliverAct.openAct(MainActivity.this, data.getResult().getId(), false);
                        break;
                    case 2://收货
                        ReceiveAct.openAct(MainActivity.this, data.getResult().getId(), false);
                        break;
                    default:
                        HuoBean huoBean = LocationMessageUtils.getIntent(MainActivity.this).getData(data.getResult().getId());
                        if (huoBean == null)
                            intoTypeDialog.show(data.getResult().getId());
                        else {
                            switch (huoBean.getType()) {
                                case 1://发货
                                    DeliverAct.openAct(MainActivity.this, data.getResult().getId(), false);
                                    break;
                                case 2://收货
                                    ReceiveAct.openAct(MainActivity.this, data.getResult().getId(), false);
                                    break;
                                default:
                                    intoTypeDialog.show(data.getResult().getId());
                            }
                        }
                        intoTypeDialog.show(data.getResult().getId());
                        break;
                }
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (bind.searchEdt.getText().toString().endsWith("***###.")) {
            bind.searchEdt.setText(bind.searchEdt.getText().toString().trim().replace("***###.", ""));
            hideKeyboard();
            onRefresh();
        }
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }
}
